package com.immortal.module.security.handler;

import com.immortal.core.module.res.ApiResult;
import com.immortal.core.service.I18nService;
import com.immortal.core.utils.http.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class CustomAccessDeniedHandler extends AccessDeniedHandlerImpl {
    private I18nService i18nService;

    public CustomAccessDeniedHandler() {
    }

    public CustomAccessDeniedHandler(I18nService i18nService) {
        this.i18nService = i18nService;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (ServletUtils.isAjaxRequest(request)) {
            log.info("权限检验失败!");
            String message=accessDeniedException.getMessage();
            if(i18nService!=null){
                message=i18nService.getMessage("auth.exception.access");
            }
            ServletUtils.renderResult(response, ApiResult.Custom().failure(message));
        }else {
            super.handle(request, response, accessDeniedException);
        }
    }
}
